﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using Microsoft.Samples.Kinect.ControlsBasics;
using Microsoft.Kinect.Toolkit.Controls;
using Microsoft.Kinect.Toolkit;
using Microsoft.Kinect;
using System.IO;
using System.Xaml;
using Microsoft.Samples.Kinect.InteractionGallery.Models;
using Microsoft.Samples.Kinect.InteractionGallery.Properties;
using System.Collections.ObjectModel;
using Microsoft.Samples.Kinect.InteractionGallery.Views;
using Microsoft.Samples.Kinect.InteractionGallery.ViewModels;
using Microsoft.Samples.Kinect.InteractionGallery.Utilities;
using Microsoft.Samples.Kinect.InteractionGallery.BLL;

namespace Microsoft.Samples.Kinect.InteractionGallery.Views
{


    /// <summary>
    /// Interaction logic for HomeScreenView.xaml
    /// </summary>
    public partial class HomeScreenView : UserControl
    {
        #region Properties

        public static readonly DependencyProperty PageLeftEnabledProperty = DependencyProperty.Register(
    "PageLeftEnabled", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));

        public static readonly DependencyProperty PageRightEnabledProperty = DependencyProperty.Register(
            "PageRightEnabled", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));

        private const double ScrollErrorMargin = 0.001;

        private const int PixelScrollByAmount = 20;

        private KinectSensorChooser sensorChooser;

        /// <summary>
        /// Gets the collection of paragraphs composing the content of the article.
        /// Changes to this property cause the PropertyChanged event to be signaled.
        /// </summary>
        public ObservableCollection<string> Paragraphs { get; private set; }

        /// <summary>
        /// Gets the collection of images associated with the article. 
        /// Changes to the paragraphs cause the CollectionChanged event to be signaled.
        /// </summary>
        public ObservableCollection<ImageSource> Images { get; private set; }

        /// <summary>
        /// Boolean determining whether any user is currently engaged.
        /// </summary>
        private bool isUserEngaged;
        /// <summary>
        /// Gets whether any user is currently engaged with the application.
        /// Changes to this property cause the PropertyChanged event to be signaled.
        /// </summary>
        public bool IsUserEngaged
        {
            get
            {
                return this.isUserEngaged;
            }

            protected set
            {
                bool wasEngaged = this.isUserEngaged;
            }
        }

        //private readonly MouseMovementDetector movementDetector;
        //private readonly FrameworkElement controller;

        #endregion

        public HomeScreenView()
        {
            this.InitializeComponent();
            Loaded += new RoutedEventHandler(OnLoaded);

            this.UpdatePagingButtonState();
            scrollViewer.ScrollChanged += (o, e) => this.UpdatePagingButtonState();

            //this.movementDetector = new MouseMovementDetector(this);
            //this.movementDetector.IsMovingChanged += this.OnIsMouseMovingChanged;
            //this.movementDetector.Start();
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            // initialize the sensor chooser and UI
            //this.sensorChooser = new KinectSensorChooser();
            //this.sensorChooser.KinectChanged += new EventHandler<KinectChangedEventArgs>(KinectSensorsOnStatusChanged);
            //this.sensorChooserUi.KinectSensorChooser = sensorChooser;
            //this.sensorChooser.Start();

            //GetImages();
            //GetImages2("/Images/");
            GetImages2(getParameters.Dic["Images_Path"]);
        }
        
        void GetImages2(string path)
        {
            this.wrapPanel.Children.Clear();
            int iImageCount = Int16.Parse(getParameters.Dic["Images_Count"]);
            string strImageExt = getParameters.Dic["Images_Ext"];
            for (int i = 1; i < iImageCount + 1; i++)
            {
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.UriSource = (i < 10) ? new Uri(string.Format("{0}pic{1}{2}", path.ToString(), i.ToString(), strImageExt), UriKind.Absolute) : new Uri(string.Format("{0}pic{1}{2}", path.ToString(), i.ToString(), strImageExt), UriKind.Absolute);
                //bi.UriSource = new Uri(string.Format("{0}幻灯片{1}{2}", path.ToString(), i.ToString(), strImageExt), UriKind.Relative);
                //bi.UriSource = new Uri("/Images/pic01.jpg", UriKind.Relative);
                bi.EndInit();
                var image = new Image();
                image.Source = bi;
                //image.MouseDown += new MouseButtonEventHandler(image_MouseDown);
                var button = new KinectTileButton();
                button.Width = int.Parse(getParameters.Dic["HomeScreenView_Image_Width"]);
                button.Height = int.Parse(getParameters.Dic["HomeScreenView_Image_Height"]);
                button.Label = image;
                this.wrapPanel.Children.Add(button);

                //var textblock = new TextBlock();
                //textblock.Text = "这里是图片简介";
                //textblock.FontSize = 22;
                //this.wrapPanel.Children.Add(textblock);
            }
        }
        void GetImages()
        {
            this.wrapPanel.Children.Clear();
            for (var index = 0; index < 50; ++index)
            {
                var image = new Image();
                BitmapImage bi3 = new BitmapImage();
                bi3.BeginInit();
                bi3.UriSource = new Uri(index % 2 == 0 ? "Images/garu.png" : "Images/pucca.png", UriKind.Relative);
                bi3.EndInit();
                //image.Stretch = Stretch.Fill;
                //image.Height = 128; image.Width = 128;
                image.Source = bi3;
                this.wrapPanel.Children.Add(image);

                //var button = new KinectTileButton { Label = (index + 1).ToString(CultureInfo.CurrentCulture) };
                //this.wrapPanel.Children.Add(button);
            }
        }

        //void KinectSensorsOnStatusChanged(object sender, KinectChangedEventArgs args)
        //{
        //    //MessageBox.Show("KinectSensors Begin");
        //    bool isError = false;
        //    if (args.OldSensor != null)
        //    {
        //        try
        //        {
        //            args.OldSensor.DepthStream.Range = DepthRange.Default;
        //            args.OldSensor.SkeletonStream.EnableTrackingInNearRange = false;
        //            args.OldSensor.DepthStream.Disable();
        //            args.OldSensor.SkeletonStream.Disable();
        //        }
        //        catch (InvalidOperationException)
        //        {
        //            // KinectSensor might enter an invalid state while enabling/disabling streams or stream features.
        //            // E.g.: sensor might be abruptly unplugged.
        //            isError = true;
        //        }
        //    }

        //    if (args.NewSensor != null)
        //    {
        //        try
        //        {
        //            args.NewSensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
        //            args.NewSensor.SkeletonStream.Enable();

        //            try
        //            {
        //                args.NewSensor.DepthStream.Range = DepthRange.Near;
        //                args.NewSensor.SkeletonStream.EnableTrackingInNearRange = true;
        //                args.NewSensor.SkeletonStream.TrackingMode = SkeletonTrackingMode.Seated;
        //            }
        //            catch (InvalidOperationException)
        //            {
        //                // Non Kinect for Windows devices do not support Near mode, so reset back to default mode.
        //                args.NewSensor.DepthStream.Range = DepthRange.Default;
        //                args.NewSensor.SkeletonStream.EnableTrackingInNearRange = false;
        //                args.NewSensor.SkeletonStream.TrackingMode = SkeletonTrackingMode.Default;
        //            }
        //        }
        //        catch (InvalidOperationException)
        //        {
        //            // KinectSensor might enter an invalid state while enabling/disabling streams or stream features.
        //            // E.g.: sensor might be abruptly unplugged.
        //            isError = true;
        //        }

        //        try
        //        {
        //            if (!isError)
        //                kinectRegion.KinectSensor = args.NewSensor;
        //        }
        //        catch (Exception)
        //        { throw; }
        //    }

        //    //MessageBox.Show("KinectSensors End");
        //}

        /// <summary>
        /// Handle a button click from the wrap panel.
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void KinectTileButtonClick(object sender, RoutedEventArgs e)
        {
            //var button = (KinectTileButton)e.OriginalSource;
            //var selectionDisplay = new SelectionDisplay(button.Label as string);
            //this.kinectRegionGrid.Children.Add(selectionDisplay);
            //e.Handled = true;

            if (this.kinectRegionGrid.Children.Count > 0)
            {
                for (int i = 0; i < this.kinectRegionGrid.Children.Count; i++)
                {
                    if (this.kinectRegionGrid.Children[i] is ShowImage)
                    { }
                    else
                    {
                        var ShowImage = new ShowImage(sender, e);
                        //ShowImage.Width = 800;
                        //ShowImage.Height = 600;
                        this.kinectRegionGrid.Children.Add(ShowImage);
                        break;
                    }
                }
            }
            e.Handled = true;
        }

        /// <summary>
        /// Execute shutdown tasks
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.sensorChooser.Stop();
        }

        #region KinectHoverButton Methods

        /// <summary>
        /// CLR Property Wrappers for PageLeftEnabledProperty
        /// </summary>
        public bool PageLeftEnabled
        {
            get
            {
                return (bool)GetValue(PageLeftEnabledProperty);
            }

            set
            {
                this.SetValue(PageLeftEnabledProperty, value);
            }
        }

        /// <summary>
        /// CLR Property Wrappers for PageRightEnabledProperty
        /// </summary>
        public bool PageRightEnabled
        {
            get
            {
                return (bool)GetValue(PageRightEnabledProperty);
            }

            set
            {
                this.SetValue(PageRightEnabledProperty, value);
            }
        }

        /// <summary>
        /// Handle paging right (next button).
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void PageRightButtonClick(object sender, RoutedEventArgs e)
        {
            scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + PixelScrollByAmount);
        }

        /// <summary>
        /// Handle paging left (previous button).
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void PageLeftButtonClick(object sender, RoutedEventArgs e)
        {
            scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset - PixelScrollByAmount);
        }

        /// <summary>
        /// Change button state depending on scroll viewer position
        /// </summary>
        private void UpdatePagingButtonState()
        {
            this.PageLeftEnabled = scrollViewer.HorizontalOffset > ScrollErrorMargin;
            this.PageRightEnabled = scrollViewer.HorizontalOffset < scrollViewer.ScrollableWidth - ScrollErrorMargin;
        }

        #endregion


    }
}
